﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ZH.GPT.Domains.User.Request;
using ZH.GPT.Domains.User.Response;
using ZH.GPT.Domains;
using ZH.GPT.Services.Interface;
using ZH.GPT.Utils;
using ZH.GPT.Version;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static ZH.GPT.Version.CustomApiVersion;
using System.Net;
using ZH.RetailContainer.CommLibrary.Result;
using ZH.RetailContainer.CommLibrary;
using Newtonsoft.Json.Linq;
using ZH.RetailContainer.CommLibrary.Extend;
using System.Net.Http;
using System.Text;
using ZH.GPT.Domains.Completions.Request;
using ZH.GPT.Domains.Completions.Response;
using Newtonsoft.Json;
using System.IO;
using OpenAI.Interfaces;
using System.Threading;
using Microsoft.AspNetCore.Http;
using OpenAI.Managers;
using OpenAI.ObjectModels.RequestModels;
using ZH.GPT.Domains.ChatMessage.Request;
using ZH.GPT.Domains.ChatMessage.Response;
using Microsoft.Extensions.Configuration;
using OpenAI.Tokenizer.GPT3;

namespace ZH.GPT.Controllers.v1
{
    //和上边的版本控制以及路由地址都是一样的
    [CustomRoute(ApiVersions.V1, "Chat")]
    public class ChatController : BaseController
    {
        private readonly ILogger<ChatController> logger;
        private readonly IOpenAIService _openAiService;
        IUserService userService;
        IChatService _chatService;
        IConfiguration _configuration;
        /// <summary>
        /// 用户构造函数
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="userService">用户服务</param>
        public ChatController(ILogger<ChatController> logger, IUserService userService, IOpenAIService openAiService, IChatService chatService, IConfiguration configuration)
        {
            this.logger = logger;
            this.userService = userService;
            _openAiService = openAiService;
            _chatService = chatService;
            _configuration = configuration;
        }

        #region 删除掉的
        ///// <summary>
        ///// 发送消息
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("Completions")]
        //[ProducesResponseType(typeof(Result<object>), 200)]
        //public async Task<ContentResult> Completions(CompletionsQDTO content)
        //{
        //    //CompletionsQDTO completionsQDTO = new CompletionsQDTO();
        //    //completionsQDTO.model = "gpt-3.5-turbo";
        //    //MessagesQDTO messagesQDTO = new MessagesQDTO();
        //    //messagesQDTO.role = "user";
        //    //messagesQDTO.content = content;
        //    //completionsQDTO.messages.Add(messagesQDTO);
        //    ResultPDTO message = Send(content);

        //    return Success(message);
        //}

        ///// <summary>
        ///// 获取租户余额
        ///// </summary>
        ///// <param name="completionsQDTO"></param>
        ///// <returns></returns>
        //private ResultPDTO Send(CompletionsQDTO completionsQDTO)
        //{
        //    ResultPDTO resultPDTO = null;
        //    //string message = "";
        //    try
        //    {
        //        Dictionary<string, string> headers = new Dictionary<string, string>();
        //        headers.Add("Authorization", "Bearer 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");

        //        string url = "https://api.openai.com/";
        //        string method = "v1/chat/completions";
        //        string result = HttpClientHelper.Request(url, method, completionsQDTO, headers);
        //        if (!string.IsNullOrWhiteSpace(result))
        //        {
        //            resultPDTO = JsonConvert.DeserializeObject<ResultPDTO>(result);

        //            //JObject resultJO = JObject.Parse(result);
        //            //if (resultJO != null && resultJO.ContainsKey("choices"))
        //            //    message = (string)resultJO["choices"][0]["message"]["content"];
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.LogError(ex, $"ZH.GPT.Chat_Completions_Error:\r\n【获取租户余额异常】{ex.CustomExceptionMessageExtend()}");
        //    }
        //    return resultPDTO;
        //}

        //[HttpPost]
        //[Route("Input2")]
        //public async Task Input2(CompletionsQDTO completionsQDTO)
        //{

        //}

        //[HttpPost]
        //[Route("Input")]
        //public async Task Input(CompletionsQDTO completionsQDTO)
        //{
        //    Dictionary<string, string> headers = new Dictionary<string, string>();
        //    headers.Add("Authorization", "Bearer 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");

        //    string url = "https://api.openai.com/";
        //    string route = "v1/chat/completions";

        //    object parameter = completionsQDTO;
        //    HttpRequestType requestType = HttpRequestType.Post;


        //    using (HttpClient httpClient = new HttpClient())
        //    {
        //        if (headers != null)
        //            foreach (KeyValuePair<string, string> keyValue in headers)
        //                httpClient.DefaultRequestHeaders.Add(keyValue.Key, keyValue.Value);


        //        var httpRequestMessage = new HttpRequestMessage
        //        {
        //            Method = HttpMethod.Post,
        //            RequestUri = new Uri(url + route),
        //            Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(parameter), Encoding.UTF8, "application/json")
        //        };


        //        string con = "";

        //        //var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(parameter), Encoding.UTF8, "application/json");
        //        HttpResponseMessage response = requestType == HttpRequestType.Post ? await httpClient.SendAsync(httpRequestMessage) : await httpClient.GetAsync(url + route);
        //        if (response.IsSuccessStatusCode)
        //        {
        //            var responseContentType = response.Content.Headers.ContentType?.MediaType;
        //            Response.Headers.Add("Content-Type", responseContentType?.ToString());
        //            if (responseContentType?.Equals("text/event-stream") ?? false)
        //            {
        //                var edgeWords = new StringBuilder();
        //                var responseStream = await response.Content.ReadAsStreamAsync();
        //                var streamWriter = new StreamWriter(Response.Body, Encoding.UTF8, 1024, true);
        //                using var streamReader = new StreamReader(responseStream, Encoding.UTF8, true, 1024, true);
        //                while (!streamReader.EndOfStream)
        //                {
        //                    var lineContent = await streamReader.ReadLineAsync();
        //                    if (lineContent == null)
        //                        continue;
        //                    con += lineContent;
        //                }
        //            }
        //        }

        //    }
        //}
        #endregion

        /// <summary>
        /// 测试单条回复
        /// </summary>
        /// <param name="message"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        [Route("ChatMessage")]
        public async Task ChatMessageAsync([FromBody] MessagesQDTO message, CancellationToken cancellationToken)
        {
            Response.Headers.Add("Content-Type", "text/event-stream");
            Response.Headers.Add("Cache-Control", "no-cache");
            try
            {
                var completionResult = _openAiService.ChatCompletion.CreateCompletionAsStream(
                new ChatCompletionCreateRequest
                {
                    Messages = new List<ChatMessage>
                    {
                        ChatMessage.FromUser(message.content)
                    },
                    Stream = true,
                    MaxTokens = 500,
                    Model = OpenAI.ObjectModels.Models.Gpt_3_5_Turbo,
                }, cancellationToken: cancellationToken);

                await foreach (var completion in completionResult)
                {
                    if (cancellationToken.IsCancellationRequested)
                        break;

                    if (completion.Successful)
                    {
                        await Response.WriteAsync(completion.Choices.FirstOrDefault()?.Message.Content ?? "", cancellationToken);
                        await Response.Body.FlushAsync(cancellationToken);
                    }
                    else
                    {
                        if (completion.Error == null)
                            throw new Exception("Unknown Error");
                        await Response.WriteAsync($"{completion.Error.Code}: {completion.Error.Message}", cancellationToken);
                        await Response.Body.FlushAsync(cancellationToken);
                    }
                }
            }
            catch (Exception ex)
            {
                await Response.WriteAsync("error:" + ex.Message);
                await Response.Body.FlushAsync();
            }
        }

        [HttpGet]
        [Route("ListRoles")]
        public async Task<List<RoleResponsePDTO>> ListRolesAsync()
        {
            return await Task.FromResult(_chatService.ListRoles);
        }

        //[HttpGet]
        //[Route("GptModels")]
        //public async Task<List<string>> GptModels()
        //{
        //    return await Task.FromResult(_chatService.GetModels());
        //}

        /// <summary>
        /// 获取模型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GptModels")]
        public async Task<List<ModelPDTO>> GptModel()
        {
            return await Task.FromResult(_chatService.GetModel());
        }

        /// <summary>
        /// ajax
        /// </summary>
        /// <param name="message"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        [Route("ChatMessageWithSystemRole")]
        public async Task ChatMessageAsync([FromBody] CompletionsQDTO msgQdto, CancellationToken cancellationToken)
        {
            Response.Headers.Add("Content-Type", "text/event-stream");
            Response.Headers.Add("Cache-Control", "no-cache");
            msgQdto.UserId = HttpContext.UserId()?.ToString();
            if (!await CheckBalanceToken(msgQdto.UserId))
            {
                await Response.WriteAsync($"您今天的余额已经用完!", cancellationToken);
                await Response.Body.FlushAsync(cancellationToken);
                return;
            }
            StringBuilder respMsg = new StringBuilder();
            try
            {
                var chatMessages = new List<ChatMessage>();
                await FormChatMessage(msgQdto, chatMessages);

                var completionResult = _openAiService.ChatCompletion.CreateCompletionAsStream(
                new ChatCompletionCreateRequest
                {
                    Messages = chatMessages,
                    Stream = true,
                    MaxTokens = 3000,
                    Model = string.IsNullOrEmpty(msgQdto.model) ? OpenAI.ObjectModels.Models.Gpt_3_5_Turbo : msgQdto.model,
                }, cancellationToken: cancellationToken);

                await foreach (var completion in completionResult)
                {
                    if (cancellationToken.IsCancellationRequested)
                        break;

                    if (completion.Successful)
                    {
                        await Response.WriteAsync(completion.Choices.FirstOrDefault()?.Message.Content ?? "", cancellationToken);
                        await Response.Body.FlushAsync(cancellationToken);
                        respMsg.Append(completion.Choices.FirstOrDefault()?.Message.Content ?? "");
                    }
                    else
                    {
                        if (completion.Error == null)
                            throw new Exception("Unknown Error");
                        await Response.WriteAsync($"{completion.Error.Code}: {completion.Error.Message}", cancellationToken);
                        await Response.Body.FlushAsync(cancellationToken);
                        //respMsg.Append($"{completion.Error.Code}: {completion.Error.Message}");
                    }
                }
                if (!string.IsNullOrEmpty(respMsg.ToString()))
                {
                    int inputTokenNum = 0;
                    chatMessages.ForEach(msg => {
                        if (msg != null && !string.IsNullOrEmpty(msg.Content))
                            inputTokenNum += TokenizerGpt3.TokenCount(msg.Content);
                    });
                    int outPutTokenNum = TokenizerGpt3.TokenCount(respMsg.ToString());
                    await _chatService.AddChatMessageAsync(msgQdto, respMsg.ToString(), outPutTokenNum + inputTokenNum);
                }
            }
            catch (Exception ex)
            {
                await Response.WriteAsync("error:" + ex.Message);
                await Response.Body.FlushAsync();
            }
            finally
            {


            }
        }

        private async Task<bool> CheckBalanceToken(string userId)
        {
            return await _chatService.CheckBalanceToken(userId);
        }

        private async Task FormChatMessage(CompletionsQDTO msgQdto, List<ChatMessage> chatMessages)
        {
            ChatMessageQDTO queryQdto = new ChatMessageQDTO();
            queryQdto.PageIndex = 1;
            queryQdto.PageSize = 1;
            queryQdto.SearchCriteria = new ChatMessageSearchCriteria() { ChatId = msgQdto.ChatId, Role = Infrastructures.Entities.MessageRole.System };
            var systemmsgPDTO = await _chatService.GetChatMessageAsync(queryQdto);



            if (systemmsgPDTO.RoutingTasks != null && systemmsgPDTO.RoutingTasks.Count > 0)
                chatMessages.Add(ChatMessage.FromSystem(systemmsgPDTO.RoutingTasks.FirstOrDefault()?.Content));

            queryQdto.PageIndex = 1;
            queryQdto.PageSize = this._configuration.GetValue<int>("MessageNumToReserve");
            queryQdto.SearchCriteria = new ChatMessageSearchCriteria { ChatId = msgQdto.ChatId, Role = Infrastructures.Entities.MessageRole.User };
            var UserMsgContents = await _chatService.GetChatMessageAsync(queryQdto);

            queryQdto.PageIndex = 1;
            queryQdto.PageSize = this._configuration.GetValue<int>("MessageNumToReserve");
            queryQdto.SearchCriteria = new ChatMessageSearchCriteria { ChatId = msgQdto.ChatId, Role = Infrastructures.Entities.MessageRole.Assistant };
            var AssistanMsgContents = await _chatService.GetChatMessageAsync(queryQdto);

            int msgNum = this._configuration.GetValue<int>("MessageNumToReserve");
            for (int i = 1; i <= msgNum; i++)
            {
                if (i % 2 == 1)
                {
                    if (UserMsgContents != null && UserMsgContents.RoutingTasks != null && UserMsgContents.RoutingTasks.Count > 0)
                    {
                        int j = i / 2;
                        if (j < UserMsgContents.RoutingTasks.Count)
                            chatMessages.Add(ChatMessage.FromUser(UserMsgContents.RoutingTasks[j].Content));
                        //for (int i = msgContents.RoutingTasks.Count - 1; i >= 0; i--)
                        //{
                        //    if (msgContents.RoutingTasks[i].Role == Infrastructures.Entities.MessageRole.System)
                        //        continue;
                        //    if (msgContents.RoutingTasks[i].Role == Infrastructures.Entities.MessageRole.User)
                        //        chatMessages.Add(ChatMessage.FromUser(msgContents.RoutingTasks[i].Content));
                        //    if (msgContents.RoutingTasks[i].Role == Infrastructures.Entities.MessageRole.Assistant)
                        //        chatMessages.Add(ChatMessage.FromAssistant(msgContents.RoutingTasks[i].Content));
                        //}
                    }
                }
                else
                {
                    if (AssistanMsgContents != null && AssistanMsgContents.RoutingTasks != null && AssistanMsgContents.RoutingTasks.Count > 0)
                    {
                        int j = (i - 1) / 2;
                        if (j < AssistanMsgContents.RoutingTasks.Count)
                            chatMessages.Add(ChatMessage.FromUser(AssistanMsgContents.RoutingTasks[j].Content));
                    }
                }
            }

            //if (msgContents != null && msgContents.RoutingTasks != null && msgContents.RoutingTasks.Count > 0)
            //{
            //    for (int i = msgContents.RoutingTasks.Count - 1; i >= 0; i--)
            //    {
            //        if (msgContents.RoutingTasks[i].Role == Infrastructures.Entities.MessageRole.System)
            //            continue;
            //        if (msgContents.RoutingTasks[i].Role == Infrastructures.Entities.MessageRole.User)
            //            chatMessages.Add(ChatMessage.FromUser(msgContents.RoutingTasks[i].Content));
            //        if (msgContents.RoutingTasks[i].Role == Infrastructures.Entities.MessageRole.Assistant)
            //            chatMessages.Add(ChatMessage.FromAssistant(msgContents.RoutingTasks[i].Content));
            //    }
            //}

            if (chatMessages.Count == 0)
            {
                foreach (var msg in msgQdto.messages)
                {
                    if (msg.role == "system")
                        chatMessages.Add(ChatMessage.FromSystem(msg.content));
                    if (msg.role == "user")
                        chatMessages.Add(ChatMessage.FromUser(msg.content));
                    if (msg.role == "assistant")
                        chatMessages.Add(ChatMessage.FromAssistant(msg.content));
                }
            }
            else
            {
                var usermsg = msgQdto.messages.LastOrDefault(p => p.role == "user");
                if (usermsg != null)
                    chatMessages.Add(ChatMessage.FromUser(usermsg.content));
            }
        }

        #region 删除掉的
        ///// <summary>
        ///// ajax
        ///// </summary>
        ///// <param name="message"></param>
        ///// <param name="cancellationToken"></param>
        ///// <returns></returns>
        ///// <exception cref="Exception"></exception>
        //[HttpPost]
        //[Route("ChatMessageNew")]
        //public async Task ChatMessageNewAsync([FromBody] MessagesQDTO message, CancellationToken cancellationToken)
        //{
        //    Response.Headers.Add("Content-Type", "text/event-stream");
        //    Response.Headers.Add("Cache-Control", "no-cache");
        //    try
        //    {
        //        //var completionResult = _openAiService.ChatCompletion.CreateCompletionAsStream(
        //        //new ChatCompletionCreateRequest
        //        //{
        //        //    Messages = new List<ChatMessage>
        //        //    {
        //        //ChatMessage.FromUser(message.content)
        //        //    },
        //        //    Stream = true,
        //        //    MaxTokens = 500,
        //        //    Model = OpenAI.ObjectModels.Models.Gpt_3_5_Turbo,
        //        //}, cancellationToken: cancellationToken);

        //        //await foreach (var completion in completionResult)
        //        //{
        //        //    if (cancellationToken.IsCancellationRequested)
        //        //        break;

        //        //    if (completion.Successful)
        //        //    {
        //        //        string data =
        //        //       $"id: {Guid.NewGuid().ToString()} \n" +
        //        //       $"retry: 10000\n" +
        //        //       $"event: message\n" +
        //        //       $"data: {completion.Choices.FirstOrDefault()?.Message.Content ?? ""}\n\n";
        //        //        await Response.WriteAsync(data);
        //        //        await Response.Body.FlushAsync();
        //        //        //await Response.WriteAsync(completion.Choices.FirstOrDefault()?.Message.Content ?? "", cancellationToken);
        //        //        //await Response.Body.FlushAsync(cancellationToken);
        //        //    }
        //        //    else
        //        //    {
        //        //        //if (completion.Error == null)
        //        //        //    throw new Exception("Unknown Error");
        //        //        //await Response.WriteAsync($"{completion.Error.Code}: {completion.Error.Message}", cancellationToken);
        //        //        //await Response.Body.FlushAsync(cancellationToken);
        //        //        if (completion.Error == null)
        //        //            throw new Exception("Unknown Error");
        //        //        string data =
        //        //        $"id: {Guid.NewGuid().ToString()} \n" +
        //        //        $"retry: 10000\n" +
        //        //        $"event: message\n" +
        //        //        $"data: {completion.Error.Code}: {completion.Error.Message}\n\n";
        //        //        await Response.WriteAsync(data);
        //        //        await Response.Body.FlushAsync();
        //        //    }
        //        //}
        //        for (int i = 0; i < 10; i++)
        //        {
        //            string data =
        //                //$"id: {Guid.NewGuid().ToString()} \n" +
        //                //$"retry: 5\n" +
        //                $"message" + i + "\n";
        //            var bitys = Encoding.UTF8.GetBytes(data);

        //            //await HttpContext.Response.Body.WriteAsync(bitys);
        //            //await HttpContext.Response.Body.FlushAsync();
        //            await Response.WriteAsync(data);
        //            await Response.Body.FlushAsync();
        //            System.Threading.Thread.Sleep(2000);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        string data = $"id: {Guid.NewGuid().ToString()} \n" +
        //               $"retry: 10000\n" +
        //               $"event: message\n" +
        //               $"data: {ex.Message}\n\n";
        //        await Response.WriteAsync(data);
        //        await Response.Body.FlushAsync();
        //        //await Response.WriteAsync("error:" + ex.Message);
        //        //await Response.Body.FlushAsync();
        //    }
        //    string data1 = "event: end\n" + "data: end\n\n";
        //    await Response.WriteAsync(data1);
        //    await Response.Body.FlushAsync();
        //    return;
        //}

        ///// <summary>
        ///// sse 方式
        ///// </summary>
        ///// <param name="message"></param>
        ///// <returns></returns>
        ///// <exception cref="Exception"></exception>
        //[HttpGet]
        //[Route("ChatData")]
        //public async Task ChatDataAsync(string message)
        //{
        //    Response.Headers.Add("Content-Type", "text/event-stream");
        //    Response.Headers.Add("Cache-Control", "no-cache");
        //    try
        //    {
        //        var completionResult = _openAiService.ChatCompletion.CreateCompletionAsStream(
        //       new ChatCompletionCreateRequest
        //       {
        //           Messages = new List<ChatMessage>
        //           {
        //                ChatMessage.FromUser(message)
        //           },
        //           Stream = true,
        //           MaxTokens = 500,
        //           Model = OpenAI.ObjectModels.Models.Gpt_3_5_Turbo,
        //       });
        //        await foreach (var completion in completionResult)
        //        {
        //            if (completion.Successful)
        //            {
        //                string data =
        //                $"id: {Guid.NewGuid().ToString()} \n" +
        //                $"retry: 10000\n" +
        //                $"event: message\n" +
        //                $"data: {completion.Choices.FirstOrDefault()?.Message.Content ?? ""}\n\n";
        //                await Response.WriteAsync(data);
        //                await Response.Body.FlushAsync();
        //            }
        //            else
        //            {
        //                if (completion.Error == null)
        //                    throw new Exception("Unknown Error");
        //                string data =
        //                $"id: {Guid.NewGuid().ToString()} \n" +
        //                $"retry: 10000\n" +
        //                $"event: message\n" +
        //                $"data: {completion.Error.Code}: {completion.Error.Message}\n\n";
        //                await Response.WriteAsync(data);
        //                await Response.Body.FlushAsync();
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        string data = $"id: {Guid.NewGuid().ToString()} \n" +
        //                $"retry: 10000\n" +
        //                $"event: message\n" +
        //                $"data: {ex.Message}\n\n";
        //        await Response.WriteAsync(data);
        //        await Response.Body.FlushAsync();
        //    }
        //    string data1 = "event: end\n" + "data: end\n\n";
        //    await Response.WriteAsync(data1);
        //    await Response.Body.FlushAsync();
        //    return;
        //}
        #endregion

        [HttpGet]
        [Route("CreateChat")]
        public async Task<ContentResult> CreateChat(string userId, string role, string model)
        {
            userId = HttpContext.UserId()?.ToString();
            var result = await _chatService.CreateChatAsync(userId, role, model);
            if (result.isSucc)
                return Success(result.id);
            else
                return Error(ErrorCode.System_Error, "操作失败");
        }

        /// <summary>
        /// 获取消息
        /// </summary>
        /// <param name="chatMessage"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetChatMessageAsync")]
        public async Task<ContentResult> GetChatMessageAsync(ChatMessageQDTO chatMessage)
        {
            try
            {
                var result = await _chatService.GetChatMessageAsync(chatMessage);
                return Success(result);
            }
            catch (Exception ex)
            {
                logger.LogError($"{ex.Message}");
                return Error(ErrorCode.System_Error, $"异常:{ex.Message}");
            }
        }

        ///// <summary>
        ///// 新增消息
        ///// </summary>
        ///// <param name="chatMessage"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("AddChatMessageAsync")]
        //public async Task<ContentResult> AddChatMessageAsync(ChatMessageDTO chatMessage)
        //{
        //    try
        //    {
        //        chatMessage.Role = Infrastructures.Entities.MessageRole.User;
        //        (bool isSucceed, string message) result = await _chatService.AddChatMessageAsync(chatMessage);
        //        if (result.isSucceed)
        //            return Success();
        //        else
        //            return Error(ErrorCode.System_Error, result.message);
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.LogError($"{ex.Message}");
        //        return Error(ErrorCode.System_Error, $"异常:{ex.Message}");
        //    }
        //}

        [HttpGet]
        [Route("ListChats")]
        public async Task<ContentResult> ListChatsAsync(string userId)
        {
            userId = HttpContext.UserId()?.ToString();
            if (string.IsNullOrEmpty(userId))
                return Error(ErrorCode.User_Null, "用户id不能为空");
            var chats = await _chatService.GetChatsAsync(userId);
            return Success(chats);
        }

        /// <summary>
        /// 创建图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("CreateImage")]
        public async Task<ContentResult> CreateImageAysnc([FromBody] CreateImageQDTO req)
        {
            ImageCreateRequest request = new ImageCreateRequest { Prompt = req.Prompt, N = req.N, Size = req.Size };
            var result = await _openAiService.Image.CreateImage(request);
            return Success(result);
        }
        /// <summary>
        /// 编辑图片
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("EditImage")]
        //public async Task<ContentResult> EditImageAysnc([FromForm(Name = "img")] IFormFile img, [FromForm(Name = "mask")] IFormFile mask, [FromForm(Name = "name")] string Name )
        public async Task<ContentResult> EditImageAysnc([FromForm] EditImageQDTO req)
        {
            ImageEditCreateRequest editReq = new ImageEditCreateRequest
            {
                Image = FileHelper.ReadFormFileToByteArray(req.Img),
                ImageName = req.Img.FileName,
                Mask = req.Mask == null ? null : FileHelper.ReadFormFileToByteArray(req.Mask),
                MaskName = req.Mask?.FileName,
                N = req.N,
                Prompt = req.Prompt,
                Size = req.Size
            };
            var resp = await _openAiService.Image.CreateImageEdit(editReq);
            return Success(resp);
        }
        /// <summary>
        /// VariationImage
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("VariationImage")]
        public async Task<ContentResult> VariationImageAsync([FromForm] VariationImageQDTO req)
        {
            ImageVariationCreateRequest variationReq = new ImageVariationCreateRequest
            {
                Image = FileHelper.ReadFormFileToByteArray(req.Img),
                ImageName = req.Img.FileName,
                N = req.N,
                Size = req.Size
            };
            var resp = await _openAiService.Image.CreateImageVariation(variationReq);
            return Success(resp);
        }

    }


    /// <summary>
    /// HttpClientHelper的请求方式
    /// </summary>
    public enum HttpRequestType
    {
        /// <summary>
        /// Post请求
        /// </summary>
        Post = 0,
        /// <summary>
        /// Get请求
        /// </summary>
        Get = 1
    }
}
